/**
 * Created by jimmy on 2020/4/27.
 */
const AliCloud = require('@alicloud/pop-core');
const { AliCloudConf } = require('../config/db')
const { accessKeyId, accessSecret } = AliCloudConf


const client = new AliCloud({
  accessKeyId: accessKeyId,
  accessKeySecret: accessSecret,
  endpoint: 'https://dysmsapi.aliyuncs.com',
  apiVersion: '2017-05-25'
});

const server = {
  _sendSms: (params = {}) => {
    return new Promise((resolve) => {
      client.request('SendSms', params, {
        method: 'POST'
      }).then((result) => {
        resolve(result);
      }, (ex) => {
        resolve(`【短信发送失败】${ex.message}`);
      });
    });
  },
  /**
   * 发送短信
   * @param params
   * @returns {Promise.<Promise.<T>|*>}
   */
  sendSMS: async (params = {}) => {
    try{
      const result = await server._sendSms(params);
      if(typeof result == 'string' && result.indexOf('失败') > -1) {
        throw new Error(result);
      }else{
        return result;
      }
    }catch (err) {
      return err;
    }
  }
};

module.exports = server;
